/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hu.arguscab.game;

import java.awt.Color;

import hu.arguscab.ai.Graph;
import hu.arguscab.ai.GraphImpl;
import hu.arguscab.ai.Node;
import hu.arguscab.ai.Path;
import hu.arguscab.ai.QuadTree;
import hu.arguscab.ai.game.AStar;
import hu.arguscab.ai.util.QuadNode;
import hu.arguscab.ai.util.Rect;
import hu.arguscab.graphic.Drawable;
import hu.arguscab.physic.Vector;

/**
 *
 * @author sharp
 */
public class Map implements Drawable {

	private int width, height;
	
	private Rect[] rects;
	private QuadTree<Integer, Vector> qTree;
	private QuadTreeRepresentation<Integer, Vector> qTreeRep;
	private QuadTreeCreator qTreeCreator;
	private AStar<Vector> astar;
	private Graph<Integer, Vector> graph;
	
	public Map() {
		width = GameScene.WIDTH;
		height = GameScene.HEIGHT;
		astar = new AStar<Vector>();
	}
	
	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}
	
	public void generate() {
		int count = (int) (Math.random()*20+1);
		rects = new Rect[count];
		for ( int i = 0; i < count; ++i ) {
			rects[i] = new Rect((int)(Math.random()*width), (int)(Math.random()*height), (int)(Math.random()*200)+20, (int)(Math.random()*200)+20);
			rects[i].setColor(Color.GRAY);
		}
		qTreeCreator = new QuadTreeCreator(this);
		qTreeCreator.generate(5);
		this.qTreeRep = qTreeCreator.getQuadRepresentation();
		graph = new GraphImpl<Integer, Vector>();
		qTree = qTreeCreator.getQuadTree();
		Node<Vector> root = qTreeCreator.getQuadTree().createGraph(graph);
		if ( root != null ) {
			for ( Node<Vector> node : graph.breathSearchIterator( root ) ) {
				QuadNode<Vector> q1 = (QuadNode<Vector>) node;
				for ( Node<Vector> childNode : graph.adjacentTo(node) ) {
					QuadNode<Vector> q2 = (QuadNode<Vector>) childNode;
					
					qTreeRep.addLine(	(int)q1.getCenter().getX(),
									(int)q1.getCenter().getY(),
									(int)q2.getCenter().getX(),
									(int)q2.getCenter().getY(),
									-1);
				}
			}
		}
	}

	@Override
	public void draw() {
		for ( Rect r : rects ) {
			r.draw();
		}
		qTreeRep.draw();
	}
	
	public Rect[] getObjects() {
		return rects;
	}
	
	public Path<Vector> getPath(Vector from, Vector to) {
		return astar.getPath(graph, qTreeCreator.getNode(from), qTreeCreator.getNode(to));
	}
}
